package com.appspot.etao.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.etao.Constant;
import com.appspot.etao.service.CronService;
import com.appspot.etao.service.ServiceFactory;

@SuppressWarnings("serial")
public class CronServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = (String)request.getParameter("action");

		CronService service = ServiceFactory.getCronService();
		
		Date startTime = new Date();
		String logMsg = "CronServlet start at:" + Constant.FORMATER_DETAIL.format(startTime);
		log(logMsg);
		System.out.println(logMsg);
		
		String msg = "";
		if (service.execute(action)) {
			msg = "执行成功！";
		} else {
			msg = "执行失败！";
		}
		
		Date endTime = new Date();
		logMsg = "CronServlet end at:" + Constant.FORMATER_DETAIL.format(startTime);
		log(logMsg);
		System.out.println(logMsg);
		
		logMsg = "耗时: " + ((double)(endTime.getTime() - startTime.getTime()))/1000 + " 秒";
		log(logMsg);
		System.out.println(logMsg);
		
		request.setAttribute("msg", msg);
		request.setAttribute("logMsg", logMsg);

		getServletContext().getRequestDispatcher("/jsp/cron.jsp").forward(request, response);
		
	}
}
